package com.chao.deeply.lock;

import java.io.Serializable;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author : Rookie
 * @description :
 * @date : 2023/8/6
 */
public class ReentrantLockDemo {

    public static int sum = 0;

    static class CountTask implements Runnable {
        public ReentrantLock lock = new ReentrantLock();

        @Override
        public void run() {
            System.out.println("线程" + Thread.currentThread().getName() + "开始！");
            for (int i = 0; i < 10000000; i++) {
                lock.lock();
                try {
                    sum +=i;
                } finally {
                    lock.unlock();
                }
            }
            System.out.println("线程" + Thread.currentThread().getName() + "结束！");
        }
    }

    public static void main(String[] args) {
        CountTask countTask = new CountTask();
        Thread t1 = new Thread(countTask);
        Thread t2 = new Thread(countTask);
        t1.start();
        t2.start();
        System.out.println(sum);
    }
}
